package com.yhyvr.service;

import com.google.common.collect.Lists;
import com.lz.mybatis.jdbc.auto.dao.*;
import com.lz.mybatis.jdbc.auto.model.*;
import com.lz.tool.ListUtils;
import com.lz.tool.MakeOrderNum;
import com.lz.tool.UUIDTool;
import com.tencent.WXPay;
import com.tencent.protocol.unifiedorder_protocol.refund_protocol.RefundReqData;
import com.tencent.protocol.unifiedorder_protocol.refund_protocol.RefundResData;
import com.yhyvr.YhyException;
import com.yhyvr.callback.YhyCallBackI;
import com.yhyvr.constant.ProxyOrderConstant;
import com.yhyvr.pojo.exception.ApiException;
import com.yhyvr.pojo.order.*;
import com.yhyvr.pojo.req.api.store.order.ApiOrderRefundGoodsUpdateReq;
import com.yhyvr.pojo.resp.CommonResp;
import com.yhyvr.pojo.resp.HttpResult;
import com.yhyvr.pojo.resp.api.store.address.ApiAddressInfoResp;
import com.yhyvr.pojo.sql.CountTasteGoods;
import com.yhyvr.service.mapper.CommonInfoServiceMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by tech6 on 2016/8/26.
 */

@Service
public class ProxyOrderService {
    @Resource
    private CommonInfoServiceMapper commonInfoServiceMapper;
    @Resource
    private BoOrderRefundLogMapper boOrderRefundLogMapper;
    @Resource
    private BoProxyOrderRefundMapper boProxyOrderRefundMapper;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private BoProxyPayLogMapper boProxyPayLogMapper;
    @Resource
    private BoProxyOrderMapper boProxyOrderMapper;
    @Resource
    private BoProxyOrderGoodsMapper boProxyOrderGoodsMapper;
    @Resource
    private BoGoodsMapper boGoodsMapper;
    @Resource
    private BoOrderLogMapper boOrderLogMapper;
    @Resource
    private BoProxyShippingAddressMapper boProxyShippingAddressMapper;
    @Resource
    private BoProxyOrderRefundGoodsMapper boProxyOrderRefundGoodsMapper;
    @Resource
    private BoBuyCartMapper boBuyCartMapper;
    @Resource
    private BoTasteGoodsMapper boTasteGoodsMapper;
    @Resource
    private BoTasterMapper boTasterMapper;
    /**
     * 订单生成
     */
    @Transactional
    public HttpResult makeERJIFENXIAO(MakeERJIFENXIAOOrderReq makeERJIFENXIAOOrderReq)throws Exception{
        MakeOrderModel makeOrderModel = new MakeOrderModel();
        if(StringUtils.isBlank(makeERJIFENXIAOOrderReq.getCardIds())){
            makeOrderModel.setGoodsId(makeERJIFENXIAOOrderReq.getGoodsId());
            makeOrderModel.setNumber(makeERJIFENXIAOOrderReq.getGoodsNumber());
        }else{
            makeOrderModel.setCardIds(makeERJIFENXIAOOrderReq.getCardIds());
        }
        makeOrderModel.setPrivilegeSign(makeERJIFENXIAOOrderReq.getPrivilegeSign());
        makeOrderModel.setProxyId(makeERJIFENXIAOOrderReq.getProxyId());
        makeOrderModel.setOrderType(makeERJIFENXIAOOrderReq.getOrderType());//二级分销
        makeOrderModel.setShippingAddressId(makeERJIFENXIAOOrderReq.getShippingAddressId());
        makeOrderModel.setOrderFreight(new BigDecimal(0));
        HttpResult httpResult = saveOrder(makeOrderModel);
        return httpResult;
    }


    /**
     * 统一下单                         httpResult
     */
    @Transactional
    public HttpResult saveOrder(MakeOrderModel makeOrderModel, YhyCallBackI yhyCallBackI)throws YhyException{
            Date now = new Date();
            String uuid = UUIDTool.getUUID();
            BoProxyOrder boProxyOrder = new BoProxyOrder();
            boProxyOrder.setCreateTime(now);
            boProxyOrder.setOrderFreight(makeOrderModel.getOrderFreight());
            boProxyOrder.setOrderDiscountPrice(new BigDecimal(0));
            boProxyOrder.setOrderPayState(0);
            boProxyOrder.setDeleteOrder(0);
            boProxyOrder.setOrderLockState(0);
            boProxyOrder.setProxyId(makeOrderModel.getProxyId());
            boProxyOrder.setOrderDeliveryState(0);
            //组织收获地址
            ApiAddressInfoResp apiAddressInfoResp = new ApiAddressInfoResp();
                BoProxyShippingAddress boProxyShippingAddress = boProxyShippingAddressMapper.selectByPrimaryKey(makeOrderModel.getShippingAddressId());
                if(boProxyShippingAddress==null){

                    throw new YhyException("收货地址不能为空");
                }
                apiAddressInfoResp.setDefaultAddress(boProxyShippingAddress.getDefaultAddress());
                apiAddressInfoResp.setAddress(boProxyShippingAddress.getShippingDetailAddress());
                apiAddressInfoResp.setConsignee(boProxyShippingAddress.getConsigneeName());
                apiAddressInfoResp.setPhone(boProxyShippingAddress.getConsigneePhone());
                apiAddressInfoResp.setProvince(boProxyShippingAddress.getShippingProvince());
                apiAddressInfoResp.setCity(boProxyShippingAddress.getShippingCity());
                apiAddressInfoResp.setAddressId(boProxyShippingAddress.getShippingAddressId());
                apiAddressInfoResp.setCounty(boProxyShippingAddress.getShippingCounty());
                apiAddressInfoResp.setPostCode(boProxyShippingAddress.getShippingPostcode());
            boProxyOrder.setShippingCity(apiAddressInfoResp.getCity());
            boProxyOrder.setShippingConsignee(apiAddressInfoResp.getConsignee());
            boProxyOrder.setShippingCounty(apiAddressInfoResp.getCounty());
            boProxyOrder.setShippingDetailAddress(apiAddressInfoResp.getAddress());
            boProxyOrder.setShippingPostcode(apiAddressInfoResp.getPostCode());
            boProxyOrder.setShippingPhone(apiAddressInfoResp.getPhone());
            boProxyOrder.setShippingProvince(apiAddressInfoResp.getProvince());
            boProxyOrder.setOrderId(uuid);
            boProxyOrder.setOrderNumber(MakeOrderNum.makeOrderNum());
        BigDecimal goodsPrice = new BigDecimal(0);
            switch (makeOrderModel.getOrderType()){
                case 2:
                    //二级分销订单
                    boProxyOrder.setOrderType(ProxyOrderConstant.ORDER_ERJIFENXIAO.getState());

                   String cardIds = makeOrderModel.getCardIds();


                    if(StringUtils.isNotBlank(cardIds)){
                       List<String> list = Lists.newArrayList(cardIds.split(","));
                       BoBuyCartExample boBuyCartExample = new BoBuyCartExample();
                        boBuyCartExample.createCriteria().andIdIn(list);
                       List<BoBuyCart> list1 = boBuyCartMapper.selectByExample(boBuyCartExample);
                        for (BoBuyCart boBuyCart : list1) {
                            BoGoods boGoods = boGoodsMapper.selectByPrimaryKey(boBuyCart.getGoodsId());
                            goodsPrice=goodsPrice.add(boGoods.getGoodsPrice()).multiply(new BigDecimal(boBuyCart.getGoodsNumber()));
                            insertOrderGoods(uuid, boBuyCart.getGoodsId(), boBuyCart.getGoodsNumber(), boGoods.getGoodsImage(), boGoods.getGoodsTitle(), boGoods.getGoodsPrice());
                        }
                        boProxyOrder.setOrderPrice(goodsPrice);
                        boProxyOrder.setOrderGoodsPrice(goodsPrice);
                        boBuyCartMapper.deleteByExample(boBuyCartExample);
                    }else{
                        BoGoods boGoods = boGoodsMapper.selectByPrimaryKey(makeOrderModel.getGoodsId());
                        goodsPrice=goodsPrice.add(boGoods.getGoodsPrice()).multiply(new BigDecimal(makeOrderModel.getNumber()));;
                        insertOrderGoods(uuid, makeOrderModel.getGoodsId(), makeOrderModel.getNumber(), boGoods.getGoodsImage(), boGoods.getGoodsTitle(), boGoods.getGoodsPrice());
                        boProxyOrder.setOrderPrice(goodsPrice);
                        boProxyOrder.setOrderGoodsPrice(goodsPrice);
                    }
                    break;
                case 5:
                    BoTasterExample boTasterExample = new BoTasterExample();
                    boTasterExample .createCriteria().andBoBpProxyIdEqualTo(makeOrderModel.getProxyId()).andBoStatusEqualTo((short) 2);
                    if(boTasterMapper.countByExample(boTasterExample)==0){
                        return CommonResp.getError("您没有试吃权限，请去个人中心试吃系统去申请。");
                    }
                    //试吃订单
                    BoTasteGoodsExample boTasteGoodsExample = new BoTasteGoodsExample();
                    boTasteGoodsExample.createCriteria().andBoStatusEqualTo((short) 1).andBoGoodsIdEqualTo(makeOrderModel.getGoodsId()).andBoEndDateGreaterThan(new Date());
                    if(boTasteGoodsMapper.countByExample(boTasteGoodsExample)>0){
                        if(commonInfoServiceMapper.countTasteGoods(new CountTasteGoods(makeOrderModel.getGoodsId(),makeOrderModel.getProxyId()))>0){
                            return CommonResp.getError("您已试吃过该商品，不能重复试吃！");
                        }
                        boProxyOrder.setOrderType(ProxyOrderConstant.ORDER_TYPE_TASTE.getState());
                        BoGoods boGoods = boGoodsMapper.selectByPrimaryKey(makeOrderModel.getGoodsId());
                        BoTasteGoods first = ListUtils.getFirst(boTasteGoodsMapper.selectByExample(boTasteGoodsExample));
                        if(first.getBoRemainNum()<=0){
                            return CommonResp.getError("该商品剩余试吃量为0，无法试吃！");
                        }
                        boTasteGoodsMapper.updateByPrimaryKey(first);
                        first.setBoRemainNum(first.getBoRemainNum()-1);
                        boTasteGoodsMapper.updateByPrimaryKey(first);
                        goodsPrice=goodsPrice.add(first.getTastePrice()).multiply(new BigDecimal(makeOrderModel.getNumber()));;
                        insertOrderGoods(uuid, makeOrderModel.getGoodsId(), makeOrderModel.getNumber(), boGoods.getGoodsImage(), boGoods.getGoodsTitle(), first.getTastePrice());
                        boProxyOrder.setOrderPrice(goodsPrice);
                        boProxyOrder.setOrderGoodsPrice(goodsPrice);
                    }else{
                        return CommonResp.getError("该商品试吃已结束");
                    }

                    break;
            }

                //插入订单
                boProxyOrderMapper.insert(boProxyOrder);
                //写入提交记录
                boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(),now,OrderLogMessage.getSubmitMessage()));
                if(yhyCallBackI!=null){
                    yhyCallBackI.callback();
                }
                return CommonResp.getSuccessByData(boProxyOrder);
    }

    public void insertScanCode(String id,Map<String,Integer> map,BigDecimal price ){
        for (Map.Entry<String, Integer> stringIntegerEntry : map.entrySet()) {
            BoGoods boGoods = boGoodsMapper.selectByPrimaryKey(stringIntegerEntry.getKey());
            insertOrderGoods(id,stringIntegerEntry.getKey(),stringIntegerEntry.getValue(),boGoods.getGoodsImage(),boGoods.getGoodsTitle(),price);
        }
    }
    /**
     * 插入订单商品
     * @param orderId
     * @param goodsId
     * @param goodsNumber
     * @param goodsImage
     * @param goodsTitle
     * @param goodsPrice
     */
    private void insertOrderGoods(String orderId,String goodsId,int goodsNumber,String goodsImage,String goodsTitle,BigDecimal goodsPrice){
        BoProxyOrderGoods boProxyOrderGoods = new BoProxyOrderGoods();
        boProxyOrderGoods.setOrderGoodsId(UUIDTool.getUUID());
        boProxyOrderGoods.setOrderId(orderId);
        boProxyOrderGoods.setGoodsId(goodsId);
        boProxyOrderGoods.setOrderGoodsNumber(goodsNumber);
        boProxyOrderGoods.setOrderGoodsImage(goodsImage);
        boProxyOrderGoods.setOrderGoodsTitle(goodsTitle);
        boProxyOrderGoods.setOrderGoodsPrice(goodsPrice);
        //插入订单商品
        boProxyOrderGoodsMapper.insert(boProxyOrderGoods);
    }


    /**
     * 在线购买订单
     */
    @Transactional
    public HttpResult saveOrder(MakeOrderModel makeOrderModel)throws Exception{

        return saveOrder(makeOrderModel,  null);
    }


    /**
     * 微信支付成功
     * @param resault
     */
    @Transactional
    public void paySuccess( Map<String, Object> resault){
        BoProxyOrderExample boProxyOrderExample = new BoProxyOrderExample();
        boProxyOrderExample.createCriteria().andOrderNumberEqualTo(resault.get("out_trade_no").toString());
        BoProxyOrder boProxyOrder = ListUtils.getFirst(boProxyOrderMapper.selectByExample(boProxyOrderExample));
        if(boProxyOrder.getOrderPayState()==0){
            boProxyOrder.setOrderPayState(1);
            boProxyOrder.setOrderPayType("WEIXIN");
            boProxyOrder.setOrderPayTime(new Date());
            boProxyOrder.setOrderPayDeviceInfo(resault.get("device_info").toString());
            boProxyOrder.setWxTransactionId(resault.get("transaction_id").toString());
            //修改订单状态
            boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
            //写入金额操作记录
            Date date = new Date();
            BoProxyPayLog boProxyPayLog = new BoProxyPayLog();
            boProxyPayLog.setPayLogId(UUIDTool.getUUID());
            boProxyPayLog.setPayLogMoney(boProxyOrder.getOrderPrice());
            boProxyPayLog.setPayLogOrderId(boProxyOrder.getOrderId());
            boProxyPayLog.setPayLogPayType(1);
            boProxyPayLog.setPayLogPlatformType(2);
            boProxyPayLog.setPayLogRemark("微信支付订单");
            boProxyPayLog.setPayLogProxyId(boProxyOrder.getProxyId());
            boProxyPayLog.setCreateTime(date);
            boProxyPayLogMapper.insert(boProxyPayLog);
            //写入提交记录
            boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(),date,OrderLogMessage.getPayMessage()));
        }else{
            //DO NO THING
        }

    }

    /**
     * 取消订单
     * @param id
     * @param proxyId
     * @return
     * @throws Exception
     */
    @Transactional
    public HttpResult refundOrder(String id,String proxyId) throws Exception {
        String UUID = UUIDTool.getUUID();
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(id);
            if(boProxyOrder.getOrderPayType().equals("WEIXIN")){
                int price = boProxyOrder.getOrderPrice().multiply(new BigDecimal(100)).intValue();
                int sprice = boProxyOrder.getOrderGoodsPrice().multiply(new BigDecimal(100)).intValue();
                RefundReqData refundReqData = new RefundReqData(boProxyOrder.getWxTransactionId(),boProxyOrder.getOrderNumber(),boProxyOrder.getOrderPayDeviceInfo(),UUID,price,sprice,proxyId);
                RefundResData refundResData = null;
                try {
                     refundResData = WXPay.doRefundBusiness(refundReqData);
                } catch (Exception e) {
                    throw e;
                }
                    if(refundResData!=null && refundResData.getReturn_code().equals("SUCCESS")){
                        if(refundResData.getResult_code().equals("SUCCESS")){
                            boProxyOrder.setOrderPayState(2);
                            boProxyOrder.setOrderLockState(0);
                            //更新订单状态
                            boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
                            Date date = new Date();
                            BoProxyPayLog boProxyPayLog = new BoProxyPayLog();
                            boProxyPayLog.setPayLogId(UUID);
                            boProxyPayLog.setPayLogMoney(boProxyOrder.getOrderPrice());
                            boProxyPayLog.setPayLogOrderId(boProxyOrder.getOrderId());
                            boProxyPayLog.setPayLogPayType(2);
                            boProxyPayLog.setPayLogPlatformType(2);
                            boProxyPayLog.setPayLogRemark("微信取消订单");
                            boProxyPayLog.setPayLogProxyId(boProxyOrder.getProxyId());
                            boProxyPayLog.setCreateTime(date);
                            boProxyPayLogMapper.insert(boProxyPayLog);
                            //写入提交记录
                            boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(),date,OrderLogMessage.getCancel()));
                        }else{
                            return CommonResp.getError(refundResData.getReturn_msg());
                        }
                    }else{
                        return  CommonResp.getError(refundResData.getReturn_msg());
                    }

            }else{
                //等待其他支付方式
                return CommonResp.getError("暂时不支持除了微信的退款");
            }
        return CommonResp.getSuccess();
    }

    /**
     * 微信退款
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public HttpResult refundWxMoney(String refundId,String userId) throws Exception {
        String UUID = UUIDTool.getUUID();
        BoProxyOrderRefund boProxyOrderRefund = boProxyOrderRefundMapper.selectByPrimaryKey(refundId);
        if(boProxyOrderRefund!=null) {
            BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(boProxyOrderRefund.getOrderId());
            if (boProxyOrder.getOrderPayType().equals("WEIXIN")) {
                int price = boProxyOrder.getOrderPrice().multiply(new BigDecimal(100)).intValue();
                int sprice = boProxyOrderRefund.getRefundPrice().multiply(new BigDecimal(100)).intValue();
                RefundReqData refundReqData = new RefundReqData(boProxyOrder.getWxTransactionId(), boProxyOrder.getOrderNumber(), boProxyOrder.getOrderPayDeviceInfo(), UUID, price, sprice, userId);
                RefundResData refundResData = null;
                try {
                    refundResData = WXPay.doRefundBusiness(refundReqData);
                } catch (Exception e) {
                    throw e;
                }
                if (refundResData != null && refundResData.getReturn_code().equals("SUCCESS")) {
                    if (refundResData.getResult_code().equals("SUCCESS")) {
                        boProxyOrder.setOrderPayState(2);
                        boProxyOrder.setOrderLockState(0);
                        //更新订单状态
                        boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
                        Date date = new Date();
                        BoProxyPayLog boProxyPayLog = new BoProxyPayLog();
                        boProxyPayLog.setPayLogId(UUID);
                        boProxyPayLog.setPayLogMoney(boProxyOrder.getOrderPrice());
                        boProxyPayLog.setPayLogOrderId(boProxyOrder.getOrderId());
                        boProxyPayLog.setPayLogPayType(2);
                        boProxyPayLog.setPayLogPlatformType(2);
                        boProxyPayLog.setPayLogRemark("微信退款");
                        boProxyPayLog.setPayLogProxyId(boProxyOrder.getProxyId());
                        boProxyPayLog.setCreateTime(date);
                        boProxyPayLogMapper.insert(boProxyPayLog);
                        //写入提交记录
                        boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(refundId, date, OrderLogMessage.getRefundGoodsSuccess(),5));
                    } else {
                        return CommonResp.getError(refundResData.getReturn_msg());
                    }
                } else {
                    return CommonResp.getError(refundResData.getReturn_msg());
                }

            } else {
                //等待其他支付方式
                return CommonResp.getError("暂时不支持除了微信的退款");
            }
        }
        return CommonResp.getSuccess();
    }
    /**
     * 退货申请
     */
    @Transactional
    public HttpResult refundOrderGoods(OrderRefundModel orderRefundModel) {
        String sql = "select sum(order_goods_number)c from bo_proxy_order_refund_goods where order_id=? and goods_id =?";
        Map<String,Object> map = jdbcTemplate.queryForMap(sql,orderRefundModel.getOrderId(),orderRefundModel.getOrderGoodsId());
        int count = Integer.parseInt(map.get("c")==null?"0":map.get("c").toString());
        BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
        boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderRefundModel.getOrderId()).andGoodsIdEqualTo(orderRefundModel.getOrderGoodsId());
        BoProxyOrderGoods  boProxyOrderGoods = ListUtils.getFirst(boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample));
        int length = boProxyOrderGoods.getOrderGoodsNumber();
        if(length-count<orderRefundModel.getRefundGoodsNumber()){
            throw new ApiException("订单没有商品可退",20001);
        }else{
        Date date = new Date();
        String id = UUIDTool.getUUID();
        BoProxyOrderRefund boProxyOrderRefund = new BoProxyOrderRefund();
        boProxyOrderRefund.setOrderRefundId(id);
        boProxyOrderRefund.setCreateTime(date);
        boProxyOrderRefund.setProxyId(orderRefundModel.getProxyId());
        boProxyOrderRefund.setOrderId(orderRefundModel.getOrderId());
        boProxyOrderRefund.setOrderAuditState(1);
        boProxyOrderRefund.setRefundCase(orderRefundModel.getrCase());
        boProxyOrderRefund.setRefundNotes(orderRefundModel.getNotes());
        boProxyOrderRefund.setOrderExpressVoucher(orderRefundModel.getVoucher());
        boProxyOrderRefund.setSysUserId(orderRefundModel.getSysUser());
        boProxyOrderRefund.setCreateTime(new Date());
        boProxyOrderRefund.setRefundPrice(boProxyOrderGoods.getOrderGoodsPrice().multiply(new BigDecimal(orderRefundModel.getRefundGoodsNumber())));
        boProxyOrderRefundMapper.insert(boProxyOrderRefund);
        BoProxyOrderRefundGoods bv = new BoProxyOrderRefundGoods();
        bv.setGoodsId(orderRefundModel.getOrderGoodsId());
        bv.setOrderGoodsNumber(orderRefundModel.getRefundGoodsNumber());
        bv.setOrderId(id);
        bv.setRefundGoodsId(UUIDTool.getUUID());
        boProxyOrderRefundGoodsMapper.insert(bv);
        boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(boProxyOrderRefund.getOrderRefundId(), date, OrderLogMessage.getCancelGoods()+"<br> 原因:"+orderRefundModel.getrCase()+"<br>备注:"+orderRefundModel.getNotes(),1));
        }
        return CommonResp.getSuccess();
    }
    /**
     * 退货信息完善
     */
    @Transactional
    public HttpResult refundOrderUpdate(ApiOrderRefundGoodsUpdateReq apiOrderRefundGoodsReq, String proxyId){
        BoProxyOrderRefundExample boProxyOrderRefundExample = new BoProxyOrderRefundExample();
        boProxyOrderRefundExample.createCriteria().andOrderRefundIdEqualTo(apiOrderRefundGoodsReq.getOrderId()).andProxyIdEqualTo(proxyId);
        BoProxyOrderRefund boProxyOrderRefund = ListUtils.getFirst(boProxyOrderRefundMapper.selectByExample(boProxyOrderRefundExample));
        boProxyOrderRefund.setShippingAddress(apiOrderRefundGoodsReq.getShippingAddress());
        boProxyOrderRefund.setOrderExpressCompany(apiOrderRefundGoodsReq.getExpressCompany());
        boProxyOrderRefund.setOrderExpressNumber(apiOrderRefundGoodsReq.getExpressNumber());
        boProxyOrderRefund.setConsignee(apiOrderRefundGoodsReq.getConsignee());
        boProxyOrderRefund.setConsigneePhone(apiOrderRefundGoodsReq.getConsigneePhone());
        boProxyOrderRefundMapper.updateByPrimaryKey(boProxyOrderRefund);
        boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(boProxyOrderRefund.getOrderRefundId(), new Date(),"完善退货申请，快递公司："+apiOrderRefundGoodsReq.getExpressCompany()+",快递单号:"+apiOrderRefundGoodsReq.getExpressNumber(),-1));
        return CommonResp.getSuccess();
    }
    /**
     * 系统确认收货
     */
    @Transactional
    public HttpResult takeOverBySys(String orderId){
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        boProxyOrder.setOrderLockState(0);
        boProxyOrder.setOrderDeliveryState(2);
        //更新订单状态
        boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
        Date date = new Date();
        //写入提交记录
        boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(),date,OrderLogMessage.getOrderTakeOverBySys()));
        return CommonResp.getSuccess();
    }
    /**
     * 确认收货
     */
    @Transactional
    public HttpResult takeOver(String orderId){
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        boProxyOrder.setOrderLockState(0);
        boProxyOrder.setOrderDeliveryState(2);
        //更新订单状态
        boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
        Date date = new Date();
        //写入提交记录
        boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(),date,OrderLogMessage.getOrderTakeOver()));
        return CommonResp.getSuccess();
    }
    /**
     * 未支付取消订单
     */
    @Transactional
    public HttpResult quxiao(String orderId){
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        if(boProxyOrder.getOrderPayState()==0) {
            boProxyOrder.setOrderPayState(2);
            boProxyOrder.setOrderLockState(0);
            //更新订单状态
            boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
            Date date = new Date();
            //写入提交记录
            boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(), date, OrderLogMessage.getCancel()));
        }
                    return CommonResp.getSuccess();
    }
    @Transactional
    /**
     * 发货
     */
    public HttpResult shipment( OrderShippingModel orderShippingModel,String orderId){
        shipmentCallBack(orderShippingModel,orderId,null);
        return CommonResp.getSuccess();
    }
    @Transactional
    /**
     * 发货
     */
    public HttpResult shipmentCallBack(OrderShippingModel orderShippingModel,String orderId, YhyCallBackI callBackI){
        return shipmentCallBack(orderShippingModel,null,orderId,callBackI);
    }
    @Transactional
    /**
     * 发货
     */
    public HttpResult shipmentCallBack(OrderShippingModel orderShippingModel,BigDecimal orderFreight,String orderId, YhyCallBackI callBackI){
        String shipmentCompany = orderShippingModel.getExpressCompany();
        String remark = orderShippingModel.getExpressRemark();
        String  shipmentNumber = orderShippingModel.getExpressNumber();
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        boProxyOrder.setOrderDeliveryState(1);
        boProxyOrder.setOrderLockState(0);
        boProxyOrder.setOrderDeliveryTime(new Date());
        if(orderFreight!=null){
            boProxyOrder.setOrderPrice(boProxyOrder.getOrderPrice().subtract(boProxyOrder.getOrderFreight()).add(orderFreight));
            boProxyOrder.setOrderFreight(orderFreight);

        }
        boProxyOrder.setOrderExpressCompany(shipmentCompany);
        boProxyOrder.setOrderExpressNumber(shipmentNumber);
        boProxyOrder.setTakeTheir(orderShippingModel.getTakeTheir());
        boProxyOrder.setOrderExpressRemark(remark);
        //更新订单状态
        boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
        Date date = new Date();
        //写入提交记录
        if(StringUtils.isNoneBlank(shipmentNumber)) {
            boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(), date, OrderLogMessage.getOrderRecive(shipmentCompany,shipmentNumber)));
        }else{
            boOrderLogMapper.insert(OrderLogMessage.buildBoOrderLog(boProxyOrder.getOrderId(), date, OrderLogMessage.getOrderRecive(remark)));
        }
        if(callBackI!=null){
            callBackI.callback();
        }
        return CommonResp.getSuccess();
    }

    @Transactional
    public HttpResult auditRefundOrder(String orderId,int state) throws Exception {
        BoProxyOrderRefund boProxyOrderRefund = boProxyOrderRefundMapper.selectByPrimaryKey(orderId);
        //1:正在审核|2:审核通过|3:取消审核|4:审核不通过|5:收到货并退款',
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(boProxyOrderRefund.getOrderId());
        if(boProxyOrderRefund.getOrderAuditState()==state){
            return CommonResp.getSuccess();
        }

        switch (state){
            case 1:
                boProxyOrderRefund.setOrderAuditState(state);
                break;
            case 2:
                if(boProxyOrderRefund.getOrderAuditState()==1) {
                    boProxyOrderRefund.setOrderAuditState(state);
                    boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(orderId, new Date(), "审核通过", state));

                }
                break;
            case 3:
                if(boProxyOrderRefund.getOrderAuditState()==1) {
                    boProxyOrderRefund.setOrderAuditState(state);
                    boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(orderId, new Date(), "取消审核", state));
                    boProxyOrder.setOrderLockState(0);
                }
                break;
            case 4:
                if(boProxyOrderRefund.getOrderAuditState()==1) {
                    boProxyOrderRefund.setOrderAuditState(state);
                    boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(orderId, new Date(), "未通过审核", state));
                    boProxyOrder.setOrderLockState(0);
                }
                break;
            case 5:
                if(boProxyOrderRefund.getOrderAuditState()==2){
                    boProxyOrderRefund.setOrderAuditState(state);
                    boOrderRefundLogMapper.insert(OrderLogMessage.buildBoOrderRefundLog(orderId, new Date(), "退款完成",state));
                    refundWxMoney(orderId,"system");
                    boProxyOrder.setOrderLockState(0);
                }
                break;

        }
        boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
        boProxyOrderRefundMapper.updateByPrimaryKeySelective(boProxyOrderRefund);
        return CommonResp.getSuccess();
    }
}
